package net.oschina.android;
import net.oschina.android.ui.activity.MainActivity;
import net.oschina.android.ui.fragment.DataLoaderFragment;
import net.oschina.android.ui.fragment.DataLoaderFragment.ProgressListener;
import net.oschina.android.ui.fragment.SplashScreenFragment;
import android.annotation.SuppressLint;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;

@SuppressLint("NewApi")
public class appStartActivity extends ActionBarActivity implements ProgressListener {
	
	private static final String TAG_DATA_LOADER = "dataLoader";
	private static final String TAG_SPLASH_SCREEN = "splashScreen";
	
	private DataLoaderFragment mDataLoaderFragment;
	private SplashScreenFragment mSplashScreenFragment;

	@Override
	public void onCompletion(Double result) {
		
		Intent intent = new Intent(this,MainActivity.class);
		startActivity(intent);
		finish();
/*		TextView tv = new TextView(this);
		tv.setText(String.valueOf(result));
		setContentView(tv);*/
		mDataLoaderFragment = null;
	}

	@Override
	public void onProgressUpdate(int progress) {
		mSplashScreenFragment.setProgress(progress);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		final FragmentManager fm = getFragmentManager();
		mDataLoaderFragment = (DataLoaderFragment) fm.findFragmentByTag(TAG_DATA_LOADER);
			if(mDataLoaderFragment == null){
				mDataLoaderFragment = new DataLoaderFragment();
				mDataLoaderFragment.setProgressListener(this);
				mDataLoaderFragment.startLoading();
				fm.beginTransaction().add(mDataLoaderFragment, TAG_DATA_LOADER).commit();
			}else{
				if(checkCompletionStatus())
					return;
			}
			
			mSplashScreenFragment = (SplashScreenFragment) fm.findFragmentByTag(TAG_SPLASH_SCREEN);
			if(mSplashScreenFragment == null){
				mSplashScreenFragment = new SplashScreenFragment();
				fm.beginTransaction().add(android.R.id.content, mSplashScreenFragment, TAG_SPLASH_SCREEN).commit();
			}
		}
	
	@Override
	protected void onStart() {
		super.onStart();
		if(mDataLoaderFragment!=null)
			checkCompletionStatus();
	}

	@Override
	protected void onStop() {
		super.onStop();
		if(mDataLoaderFragment!=null)
			mDataLoaderFragment.removeProgressListener();
	}

	/**
	 *2014年8月27日
	 *@return
	 */
	private boolean checkCompletionStatus() {
		if(mDataLoaderFragment.hasResult()){
			onCompletion(mDataLoaderFragment.getResult());
			FragmentManager fm = getFragmentManager();
			mSplashScreenFragment = (SplashScreenFragment) fm.findFragmentByTag(TAG_SPLASH_SCREEN);
			if(mSplashScreenFragment!=null)
				fm.beginTransaction().remove(mSplashScreenFragment).commit();
			return true;
		}
		mDataLoaderFragment.setProgressListener(this);
		return false;
	}
}
